package com.centling.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.centling.business.SmsVO;
import com.centling.core.BaseDAO;
import com.centling.dao.ISmsDAO;

@Repository
@Transactional
public class SmsDAO extends BaseDAO implements ISmsDAO {

	@SuppressWarnings({ "unchecked" })
	public List<SmsVO> getUnSendSms(String beginTime, String endTime) {
		Session session = this.sessionFactory.getCurrentSession();
		StringBuffer hql = new StringBuffer();
		hql.append("SELECT ID,bizType,senderId,isRevertible,title,content,msgType,CONVERT(varchar(500), isnull(receivers, '')) as receivers,receiverId, ");
		hql.append("	FFuncNumber,isSent,FReplyType,FInterID,sentTime,createTime,FSendState,FOriginalGUID,FUserPort ");
		hql.append("FROM TB_SendMessage ");
		hql.append("WHERE isSent=0 and FSendState=0 and createTime>:beginTime and createTime<:endTime");
		Query query = session.createSQLQuery(hql.toString())
				.setParameter("beginTime", beginTime)
				.setParameter("endTime", endTime);
		List<Object[]> list = query.list();
		List<SmsVO> vos = null;
		if (list!=null && !list.isEmpty()){
			vos = new ArrayList<SmsVO>();
			for (Object[] row : list){
				SmsVO vo = new SmsVO();
				vo.setId((String)row[0]);
				vo.setPhones((String)row[7]);
				vo.setContent((String)row[4]);
				vos.add(vo);
			}
		}
		return vos;
	}

	public void updateSmsByID(String id, String isSent, Integer fsendstate) {
		Session session = this.sessionFactory.getCurrentSession();
		StringBuffer hql = new StringBuffer();
		hql.append("update TB_SendMessage ");
		hql.append("set isSent=:isSent,sentTime=:sentTime,FSendState=:fsendstate ");
		hql.append("where ID=:ID");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		session.createSQLQuery(hql.toString())
			.setParameter("isSent", isSent)
			.setParameter("sentTime", sdf.format(new Date()))
			.setParameter("fsendstate", fsendstate)
			.setParameter("ID", id)
			.executeUpdate();
	}
	
}
